# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor
from jms.dm.prescription.dm_business_reach_summary_dt import jms_dm__dm_business_reach_summary_dt

# doris表名
doris_table = "dm_business_reach_summary_dt"
# label名
label = f"{doris_table}_{int(time())}"
# hive中表名
hive_table = "dm_business_reach_summary_dt"
# hdfs文件路径
hdfs_path = "hdfs://{{var.value.hadoop_namespace}}/dw/hive/jms_dm.db/external/"
timeout = timedelta(minutes=30).seconds
# 判断当天分区是否存在
file_path = f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | cst_ds }}}}/*/*"'
partition_lists = []
path_lists = []
for i in range(0, 11):
    if i == 0:
        partition_lists.append("p{{ execution_date | cst_ds_nodash }}")
        path_lists.append(file_path)
    else:
        partition_lists.append("p{{ execution_date | date_add(-" + str(i) + ") | cst_ds_nodash }}")
        path_lists.append(f'"{hdfs_path}{hive_table}/dt={{{{ execution_date | date_add(-{i}) | cst_ds }}}}/*/*"')

partition_str = ",".join(partition_lists)
path_str = ",".join(path_lists[::-1])
doris_jms_dm__dm_business_reach_summary_dt = RichSqlSensor(
    task_id='doris_jms_dm__dm_business_reach_summary_dt',
    pool='broker_load_pool',
    email=['jokic.wang@jtexpress.com', 'yl_bigdata@yl-scm.com'],
    task_concurrency=1,
    conn_id='doris',
    pre_sql=f"""
                 TRUNCATE TABLE jms_dm.{doris_table} PARTITION ({partition_str});
                 LOAD LABEL jms_dm.{label} (
                     DATA INFILE({path_str})
                     INTO TABLE {doris_table}
                     FORMAT AS 'PARQUET'
                 )
                 WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
                 PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM jms_dm WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM jms_dm WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(minutes=30), )

doris_jms_dm__dm_business_reach_summary_dt << jms_dm__dm_business_reach_summary_dt
